<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>[6.2]-SDK包（JAVA版） | PhalApi(π框架) - PHP轻量级开源接口框架 - 助你创造价值！</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <meta content="telephone=no" name="format-detection">
    <meta content="email=no" name="format-detection">
    <meta name="Author" content="PhalApi,ecitlm,dogstar">
    <meta name="description" content="[6.2]-SDK包（JAVA版），PhalApi是一个PHP轻量级开源接口框架，致力于快速开发接口服务。支持HTTP/SOAP/RPC等协议，可用于搭建接口/微服务/RESTful接口/Web Services。我们不断更新，保持生气；为接口负责，为开源负责！并承诺永久免费！">
    <meta name="keywords" content="PhalApi,phalapi,phalapi接口开发,后台接口开发,后台接口开发框架,接口开发,接口框架,开源接口框架,PHP后台接口开发,PHP接口开发,PHP接口框架,PHP后台接口框架,phalapi官网,PHP接口框架,php接口开发框架,php接口开发,php web框架,π框架,π开发框架,π接口框架,π接口开发框架,api接口,php接口,,PHP接口框架,phalapi文档,phalapi wiki,PhalApi文档,phalapi在线文档,phalapi官方文档">

    <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" media="screen">
    <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css" media="screen">
    <link rel="stylesheet" href="../css/main.css" />
    <link rel="stylesheet" href="../css/loading_bar.css" />
    <link rel="icon" href="http://webtools.qiniudn.com/dog_catch.png" type="image/x-icon" />
    <script src="../js/pace.min.js"></script>
	
	<!-- 代码高亮 -->
	<link rel="stylesheet" href="../css/highlight.min.css">
	<script src="../js/highlight.min.js"></script>
	<script>hljs.initHighlightingOnLoad();</script>
    
</head>

<body>
    <!-- navbar start -->
    <div class="navbar navbar-default navbar-fixed-top" id="mainnav" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand website_name" href="/"><!-- <span>PhalApi</span> --><strong>PhalApi</strong></a>
            </div>
            <div class="navbar-collapse collapse" aria-expanded="false" style="height: 1px;">
                <ul class="nav navbar-nav navbar-right" id="nav_bar">
                    <li><a href="/"><span class="glyphicon glyphicon-home"></span></a></li>
                    <li><a href="http://qa.phalapi.net/">社区</a></li>
                    <li><a href="/download.html">下载</a></li>
                    <li class="active"><a href="/wikis/">文档</a></li>
                    <li><a href="http://www.ituring.com.cn/book/2405">书籍</a></li>
                    <li><a href="http://demo.phalapi.net/">体验</a></li>
                    <li><a href="/about.html">关于</a></li>
                    <li><a href="/donate.html">贡献</a></li>
                    <li><a href="/wikis/en/">English</a></li>
                </ul>
            </div>
            <!--/.nav-collapse -->
        </div>
    </div>
    <!-- navbar end -->


    <div id="content">
        <div class="container">
            <div class="row row-md-flex row-md-flex-wrap">
                <h4><a href="/wikis/%5B6.1%5D-%E5%9F%BA%E4%BA%8E%E6%8E%A5%E5%8F%A3%E6%9F%A5%E8%AF%A2%E8%AF%AD%E8%A8%80%E7%9A%84SDK%E5%8C%85.html">上一章</a>   <a href="/wikis/">文档首页</a>   <a href="/wikis/%5B6.3%5D-SDK%E5%8C%85%EF%BC%88PHP%E7%89%88%EF%BC%89.html">下一章</a></h4>
<hr />
<h2>6.2.1 使用说明</h2>
<p>将框架目录下的 ./SDK/JAVA/net 目录中的全部代码拷贝到项目里面即可使用。如：  </p>
<p><img src="http://7qnay5.com1.z0.glb.clouddn.com/qq20151017100539.jpg" alt="" />  </p>
<h2>6.2.2 代码示例</h2>
<p>如下是使用的代码场景片段。  </p>
<p>首先，我们需要导入SDK包：</p>
<pre><code class="language-java">//FullscreenActivity.java
import net.phalapi.sdk.*;</code></pre>
<p>然后，准备一个子线程调用，并在此线程中实现接口请求：</p>
<pre><code class="language-java">    /**
     * 网络操作相关的子线程
     */  
    Runnable networkTask = new Runnable() {  

        @Override  
        public void run() {  
            // TODO  
            // 在这里进行 http request.网络请求相关操作  

            PhalApiClient client = PhalApiClient.create()
                        .withHost("http://demo.phalapi.net/");

            PhalApiClientResponse response = client
                        .withService("Default.Index")
                        .withParams("username", "dogstar")
                        .withTimeout(3000)
                        .request();

            String content = "";
            content += "ret=" + response.getRet() + "\n";
            if (response.getRet() == 200) {
                try {
                    JSONObject data = new JSONObject(response.getData());
                    content += "data.title=" + data.getString("title") + "\n";
                    content += "data.content=" + data.getString("content") + "\n";
                    content += "data.version=" + data.getString("version") + "\n";
                } catch (JSONException ex) {

                }
            }
            content += "msg=" + response.getMsg() + "\n";

            Log.v("[PhalApiClientResponse]", content);

            Message msg = new Message();  
            Bundle data = new Bundle();  
            data.putString("value", content);  
            msg.setData(data);  
            handler.sendMessage(msg);  
        }  
    }; </code></pre>
<p>接着，实现线程回调的hander：</p>
<pre><code class="language-java">    Handler handler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            super.handleMessage(msg);  
            Bundle data = msg.getData();  
            String val = data.getString("value");  
            Log.i("mylog", "请求结果为--&gt;" + val);  
            // TODO  
            // UI界面的更新等相关操作  
        }  
    }; </code></pre>
<p>最后，在我们需要的地方启动：</p>
<pre><code class="language-java">    View.OnClickListener mDummyBtnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // 开启一个子线程，进行网络操作，等待有返回结果，使用handler通知UI  
            new Thread(networkTask).start();  

            // ....
        }
    };</code></pre>
<h3>再一次调用和异常请求</h3>
<p>当我们需要再次使用同一个接口实例进行请求时，需要先进行重置，以便清空之前的接口参数，如：</p>
<pre><code class="language-java">//再一次请求
response = client.reset() //重置
        .withService("User.GetBaseInfo")
        .withParams("user_id", "1")
        .request();

content = "";
content += "ret=" + response.getRet() + "\n";
if (response.getRet() == 200) {
    try {
        JSONObject data = new JSONObject(response.getData());
        JSONObject info = new JSONObject(data.getString("info"));

        content += "data.info.id=" + info.getString("id") + "\n";
        content += "data.info.name=" + info.getString("name") + "\n";
        content += "data.info.from=" + info.getString("from") + "\n";
    } catch (JSONException ex) {

    }
}
content += "msg=" + response.getMsg() + "\n";

Log.v("[PhalApiClientResponse]", content);</code></pre>
<p>异常情况下，即ret != 200时，将返回错误的信息，如：</p>
<pre><code class="language-java">//再来试一下异常的请求
response = client.reset()
        .withService("XXX.XXXX")
        .withParams("user_id", "1")
        .request();

content = "";
content += "ret=" + response.getRet() + "\n";
content += "msg=" + response.getMsg() + "\n";

Log.v("[PhalApiClientResponse]", content);</code></pre>
<h2>6.2.3 运行效果</h2>
<p>运行后，查询log，可以看到：  </p>
<p><img src="http://7qnay5.com1.z0.glb.clouddn.com/QQ20151017154114.jpg" alt="" />  </p>
<p>可以注意到，在调试模式时，会有接口请求的链接和返回的结果日记，如：  </p>
<pre><code>10-17 07:40:55.268: D/[PhalApiClient requestUrl](1376): http://demo.phalapi.net/?service=User.GetBaseInfo&amp;user_id=1
10-17 07:40:55.364: D/[PhalApiClient apiResult](1376): {"ret":200,"data":{"code":0,"msg":"","info":{"id":"1","name":"dogstar","from":"oschina"}},"msg":""}</code></pre>
<h2>6.2.4 扩展你的过滤器和结果解析器</h2>
<h3>(1)扩展过滤器</h3>
<p>当服务端接口需要接口签名验证，或者接口参数加密传送，或者压缩传送时，可以实现此过滤器，以便和服务端操持一致。  </p>
<p>当需要扩展时，分两步。首先，需要实现过滤器接口：  </p>
<pre><code class="language-java">class MyFilter implements PhalApiClientFilter {

        public void filter(String service, Map&lt;String, String&gt; params) {
            //TODO ...
        }
}</code></pre>
<p>然后设置过滤器：</p>
<pre><code class="language-java">PhalApiClientResponse response = PhalApiClient.create()
           .withHost("http://demo.phalapi.net/")
           .withFilter(new MyFilter())
           // ...
           .request();</code></pre>
<h3>(2)扩展结果解析器</h3>
<p>当返回的接口结果不是JSON格式时，可以重新实现此接口。  </p>
<p>当需要扩展时，同样分两步。类似过滤器扩展，这里不再赘述。</p>
<h2>6.2.5 特别注意：Android之NetworkOnMainThreadException异常</h2>
<p>由于此SDK包是使用HttpURLConnection发起请求时，所以在主线程调用时会触发NetworkOnMainThreadException异常，具体可参考： <a href="http://blog.csdn.net/mad1989/article/details/25964495">Android之NetworkOnMainThreadException异常</a>  </p>
<p>所以，需要使用子线程来发起请求，或者重新继承改用异步的请求。  </p>
<hr />
<h4><a href="/wikis/%5B6.1%5D-%E5%9F%BA%E4%BA%8E%E6%8E%A5%E5%8F%A3%E6%9F%A5%E8%AF%A2%E8%AF%AD%E8%A8%80%E7%9A%84SDK%E5%8C%85.html">上一章</a>   <a href="/wikis/">文档首页</a>   <a href="/wikis/%5B6.3%5D-SDK%E5%8C%85%EF%BC%88PHP%E7%89%88%EF%BC%89.html">下一章</a></h4><div style="float: left">
<h4>
<a href="http://qa.phalapi.net/">还有疑问？欢迎到社区提问！</a>
</h4>
</div>
            </div>
        </div>
    </div>

 <!-- 广告位 -->
<div class="grid-wrapper desktop-only">
	<p align="center">
		<a href="http://7xiz2f.com1.z0.glb.clouddn.com/%E6%88%91%E7%9A%84%E5%90%8D%E5%AD%97%E5%8F%AB%EF%BC%9A%CF%80%E6%A1%86%E6%9E%B6%20-%20PhalApi%202016%E5%B9%B4%E5%BA%A6%E5%BC%80%E6%BA%90%E6%80%BB%E7%BB%93%20-%20%E5%AE%98%E6%96%B9%E5%87%BA%E5%93%81.pdf" target="blank"><img width="950" height="100" src="http://7xiz2f.com1.z0.glb.clouddn.com/ad_20170104.png"></a>
		<a href="http://www.itran.cc/" target="blank"><img width="950" height="100" src="http://7xslqv.com1.z0.glb.clouddn.com/images/9/69/b88bc92455dc1239f9a5bf8d72929.png"></a>
		<a href="http://web-tools.phalapi.net/" target="blank"><img width="950" height="100" src="http://7xslqv.com1.z0.glb.clouddn.com/images/7/d0/88f523566c482296aecc43d185ca2.png"></a>
	</p>
</div>

        <!-- footer -->
        <div class="footer">
            <div class="link container ">
                <div class=" col-xs-7 col-sm-7 col-md-7 col-lg-7 ">
                    <h3>PhalApi (π框架)</h3>
                    <p>一个轻量级PHP开源接口框架，专注于接口服务开发，支持HTTP/SOAP/RPC协议，拥有自动生成的在线文档、多种开发语言的客户端SDK包以及可重用的扩展类库，可用于快速搭建微服务、RESTful接口或Web
                        Services。</p>
                    <!-- <p>:</p> -->
                    <span>友情链接:</span>
                    <a href="https://www.phalapi.net/" target="_blank"> PhalApi </a>
                    <a href="http://www.oschina.net/" target="_blank"> 开源中国 </a>
                    <a href="https://www.itran.cc/" target="_blank">艾翻译</a>
                    <a href="http://www.phalconphp.com/en/" target="_blank">Phalcon</a>
                    <a href="https://phpunit.de/manual/3.7/zh_cn/automating-tests.html" target="_blank">PHPUnit</a>
                    <a href="http://www.thoughtworks.com/cn/" target="_blank">ThoughtWorks</a>
                    <a href="mailto:chanzonghuang@gmail.com">友链交换</a>

                </div>
                <div class=" col-xs-5 col-sm-5 col-md-5 col-lg-5 contact_us ">
                    <h3>联系我们</h3>
                    <a href="https://github.com/phalapi/phalapi"><img src="../images/github.png" alt="github" /></a>
                    <a href="http://weibo.com/p/100808d236e99beb645bfb56ed1c37dde9b8bd?k=phalapi%E5%BC%80%E6%BA%90%E6%A1%86%E6%9E%B6&from=501&_from_=huati_topic"><img src="../images/weibo.png"  alt="weibo" /></a>
                    <a href="http://7xslqv.com1.z0.glb.clouddn.com/images/1/b0/894fde762850cb11250253f7d5ede.png"><img src="../images/zfb.png"  alt="zfb" /></a>
                    <a href="https://jq.qq.com/?_wv=1027&k=4A6reum"><img src="../images/qq.png"  alt="qq" /></a>
					<a href="http://git.oschina.net/dogstar/PhalApi"><img src="../images/git-oschina.png"  alt="git-oschina" /></a>
                </div>
                <div class="cls"></div>
                <div class="text-center copy_right"> ©2015-2017 PhalApi All Rights Reserved. <a href="http://www.miitbeian.gov.cn" target="_blank">粤ICP备15028808号</a>

				<script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1255326144'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s4.cnzz.com/z_stat.php%3Fid%3D1255326144%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));</script>
                </div>
            </div>
        </div>
    </div>


    <a href="https://github.com/phalapi"><img id="gitHub_fllow" style="position: fixed; top: 0; right: 0; border: 0;z-index:9999" src="https://camo.githubusercontent.com/652c5b9acfaddf3a9c326fa6bde407b87f7be0f4/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6f72616e67655f6666373630302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png"></a>


    <script src="../js/jquery-1.11.1.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
</body>

</html>